﻿using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace Storm.TextEditor.Interacting
{
	[ToolboxItem(false)]
	public class RegionHandler
		: Component
	{
		#region Fields

		private Color   transparencyKey = Color.FromArgb(255, 0, 255);
		private Control control         = null;
		private Bitmap  maskImage       = null;

		private Container components;

		#endregion

		#region Properties

		/// <summary>
		/// Gets or sets the transparency key of the RegionHandler.
		/// </summary>
		public Color TransparencyKey
		{
			get { return transparencyKey; }
			set { transparencyKey = value; }
		}

		/// <summary>
		/// Gets or sets the target Control of the RegionHandler.
		/// </summary>
		public Control Control
		{
			get { return control; }
			set { control = value; }
		}

		/// <summary>
		/// Gets or sets the masking image of the RegionHandler.
		/// </summary>
		public Bitmap MaskImage
		{
			get { return maskImage; }
			set { maskImage = value; }
		}

		#endregion

		#region Methods

		#region Public

		/// <summary>
		/// Applies the region to the current Control target.
		/// </summary>
		public void ApplyRegion()
		{
			Region region = new Region(new Rectangle(0, 0, this.MaskImage.Width, this.MaskImage.Height));

			for (int y = 0; y < this.MaskImage.Height; y++)
			{
				for (int x = 0; x < this.MaskImage.Width; x++)
				{
					if (this.MaskImage.GetPixel(x, y) == this.TransparencyKey)
						region.Exclude(new Rectangle(x, y, 1, 1));
				}
			}

			this.Control.Region = region;
			this.Control.BackgroundImage = this.MaskImage;
		}

		/// <summary>
		/// Applies the region to the given Control target.
		/// </summary>
		/// <param name="target">Control to apply region to.</param>
		/// <param name="maskImage">MaskImage property.</param>
		/// <param name="transparencyKey">TransparencyKey color.</param>
		public void ApplyRegion(Control target, Bitmap maskImage, Color transparencyKey)
		{
			this.Control = target;
			this.MaskImage = maskImage;
			this.TransparencyKey = transparencyKey;

			this.ApplyRegion();
		}

		#endregion

		#endregion

		/// <summary>
		/// Initializes a new instance of RegionHandler.
		/// </summary>
		public RegionHandler()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Initializes a new instance of RegionHandler.
		/// </summary>
		/// <param name="container">Container of the RegionHandler.</param>
		public RegionHandler(IContainer container)
		{
			container.Add(this);
			InitializeComponent();
		}

		#region Component Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			components = new System.ComponentModel.Container();
		}

		#endregion
	}
}
